<template>
    <LayoutWrap class="bill-detail">
        <el-form
            v-loading="isLoading"
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '60px' : '80px'"
        >
            <el-form-item prop="name" label="name">
                <el-input :disabled="isDetail" v-model="form.name" placeholder="请输入功能名称"></el-input>
            </el-form-item>
            <el-form-item prop="moduleId" label="moduleId">
                <el-select v-model="form.moduleId" filterable clearable placeholder="请选择" style="width: 100%;">
                    <el-option
                        :disabled="isDetail"
                        v-for="item in optionsModules"
                        :key="item._id"
                        :label="`${item.meta.title},${item.name},${item.id}`"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="apis" label="apis">
                <FormTable :isDetail="isDetail" :options="optionsApis" ref="formTable" v-model="form.apis"></FormTable>
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="isDetail"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写备注"
                ></el-input>
            </el-form-item>
            <el-form-item prop="" label="">
                <div>
                    <el-button @click="onClickOk" style="width: 100%;" type="primary">确定</el-button>
                </div>
            </el-form-item>
        </el-form>
    </LayoutWrap>
</template>

<script>
import {getApiList, postFunctionMaps, putFunctionMaps, getFunctionMapById, getLayoutModules} from '@/api/permission';
import {mapState} from 'vuex';
import {PERMISSION_FUNCTION_ADD, PERMISSION_FUNCTION_DETAIL, PERMISSION_FUNCTION_EDIT} from '@/router/route-name';
import {METHODS_TYPE} from '@/views/system/interface/constants';
// import {deepCopy} from '@/utils/utils';
import FormTable from './FormTable';
const dataSourceDefault = {
    name: '',
    moduleId: '',
    apis: [
        {
            path: '',
            methods: ['get', 'post', 'delete', 'put']
        }
    ],
    remark: ''
};
export default {
    name: 'functionMap-detail',
    components: {FormTable},
    data() {
        const validateApis = (rule, value, callback) => {
            if (Array.isArray(value)) {
                callback();
            } else {
                callback(new Error('apis格式不正确'));
            }
        };
        return {
            dataSourceDefault,
            METHODS_TYPE,
            // 新建表单
            form: {
                id: undefined,
                name: '',
                moduleId: '',
                apis: [],
                remark: ''
            },
            rules: {
                name: [{required: true, message: 'name必填项', trigger: ['change', 'blur']}],
                moduleId: [{required: true, message: 'moduleId必填项', trigger: ['change', 'blur']}],
                apis: [
                    {required: true, message: 'apis必填项', trigger: ['change', 'blur']},
                    {validator: validateApis, trigger: ['change', 'blur']}
                ],
                methods: [{required: true, message: 'methods必填项', trigger: ['change', 'blur']}]
                // remark: [{required: false, message: '请填角色备注', trigger: ['change', 'blur']}]
            },
            optionsModules: [],
            optionsApis: [],
            tableData: [],
            isLoading: false,
            defaultObj: {}
        };
    },
    computed: {
        ...mapState('app', {
            isMobile: state => state.isMobile
        }),
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    async created() {
        const {name: routeName, query} = this.$route;
        const isHasDetail = routeName !== PERMISSION_FUNCTION_ADD && query.id;
        console.log('isHasDetail', isHasDetail);
        if (isHasDetail) {
            try {
                this.isEdit = routeName !== PERMISSION_FUNCTION_DETAIL;
                this.isLoading = true;
                await this.getLayoutModules();
                await this.getApiList();
                if (isHasDetail) {
                    await this.getDetail(query.id);
                }
            } catch (error) {
            } finally {
                this.isLoading = false;
            }
        } else {
            await this.getLayoutModules();
            await this.getApiList();
        }
    },
    methods: {
        getDetail(id) {
            this.isLoading = true;
            getFunctionMapById(id)
                .then(({data: res}) => {
                    this.form = {...this.form, ...res.data};
                })
                .catch(error => {
                    console.error(error);
                    this.$message({showClose: true, type: 'error', message: '获取数据失败'});
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
        onClickOk() {
            const p1 = new Promise((resolve, reject) => {
                this.$refs.formRule.validate((valid, fields) => {
                    if (valid) {
                        resolve();
                    } else {
                        reject(fields);
                    }
                });
            });
            const p2 = this.$refs.formTable.validator();

            Promise.all([p1, p2])
                .then(() => {
                    const {_id, name, moduleId, apis, remark} = this.form;
                    const newItem = {_id, name, moduleId, apis, remark};

                    const routeName = this.$route.name;

                    if (routeName === PERMISSION_FUNCTION_ADD) {
                        this.onCreate(newItem);
                    }
                    if (routeName === PERMISSION_FUNCTION_DETAIL || routeName === PERMISSION_FUNCTION_EDIT) {
                        this.onPutData(newItem);
                    }
                })
                .catch(error => {
                    console.error(error);
                });
            // console.log('this.$refs[formName]', this.$refs[formName].validator());
        },
        onClickDelete(row) {},
        getLayoutModules() {
            const newItem = {page: 1, pageSize: 1000, sort: 'id'};
            return getLayoutModules(newItem)
                .then(({data: res}) => {
                    this.optionsModules = res.data;
                })
                .catch(error => {
                    console.log('error', error);
                });
        },
        getApiList() {
            const newItem = {page: 1, pageSize: 1000, sort: '-dete', select: '_id methods path remark'};
            return getApiList(newItem)
                .then(({data: res}) => {
                    this.optionsApis = res.data;
                })
                .catch(error => {
                    console.log('error', error);
                });
        },
        handleClick() {
            this.isEdit = !this.isEdit;
        },
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true;
                setTimeout(() => {
                    this.loading = false;
                    this.options = this.list.filter(item => {
                        return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
                    });
                }, 200);
            } else {
                this.options = [];
            }
        },

        onClickClose(api, index) {
            const apis = [...this.form.apis];

            apis.splice(index, 1);

            this.form = {...this.form, apis};
        },
        onClickPushApi() {
            this.form = {
                ...this.form,
                apis: [
                    {
                        path: '',
                        methods: ['get', 'post', 'delete', 'put'],
                        key: Math.random().toString()
                    },
                    ...this.form.apis
                ]
            };
        },
        // 创建角色
        onCreate(newItem) {
            this.centerDialogLoading = true;
            postFunctionMaps(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;

                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '创建失败'});
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        onPutData(newItem) {
            this.centerDialogLoading = true;
            putFunctionMaps(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        }
    }
};
</script>

<style lang="scss" scoped>
.edit-bar {
    display: flex;
    flex-flow: row wrap;
    & > li + li {
        margin-left: 16px;
    }
}
</style>
<style lang="scss" scoped>
.box-card {
    ::v-deep {
        .el-card__body {
            padding-top: 0;
        }
    }
    margin-bottom: 20px;
}
</style>
